# -*- coding:utf-8 -*-
# @FileName :logging.py
# @Date: 2023/7/6
# @Author:天空之城
import os
import logging
import datetime

from AtomClicker.config.config import LOGS_DIR


class Logger:
    def __init__(self, log_encode='UTF-8'):
        log_file_path = Logger.get_log_file_path()
        if not os.path.exists(LOGS_DIR): os.makedirs(LOGS_DIR)
        self.__log_encode = log_encode
        self.__log_file_path = log_file_path
        self.__make_log_dir__()
        self._logger = logging.getLogger(__name__)
        self._logger.setLevel(logging.DEBUG)
        # formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s')
        formatter = logging.Formatter(
            '%(asctime)s - %(filename)s - %(levelname)s - %(funcName)s - %(lineno)d - %(message)s')
        file_handler = logging.FileHandler(log_file_path, encoding=log_encode)  # Added encoding='utf-8'
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(formatter)
        self._logger.addHandler(file_handler)
        self._logger.addHandler(console_handler)

    @staticmethod
    def get_log_file_path():
        today = datetime.date.today()
        today = str(today)
        log_file_path = os.path.join(LOGS_DIR, today, f"{today}.log")
        return log_file_path

    def __make_log_dir__(self):
        file_path = os.path.dirname(self.__log_file_path)
        if os.path.exists(file_path): return True
        try:
            os.mkdir(file_path)
        except:
            os.makedirs(file_path)

    def debug(self, message):
        self._logger.debug(message, stacklevel=2)

    def info(self, message):
        self._logger.info(message, stacklevel=2)

    def warning(self, message):
        self._logger.warning(message, stacklevel=2)

    def error(self, message):
        self._logger.error(message, stacklevel=2)

    def critical(self, message):
        self._logger.critical(message, stacklevel=2)


logger = Logger()
